import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useUserStore = defineStore('user', () => {
  // 从localStorage加载用户信息
  const loadUserFromStorage = () => {
    const stored = localStorage.getItem('user-info')
    if (stored) {
      try {
        return JSON.parse(stored)
      } catch (e) {
        console.error('Failed to parse user info from localStorage:', e)
        return null
      }
    }
    return null
  }

  // 用户信息
  const userInfo = ref(loadUserFromStorage() || {
    id: '',
    username: '',
    name: '',
    role: '', // admin, employee, safety
    permissions: {},
    lastLoginTime: '',
    status: '',
    department: '',
    position: '',
    phone: '',
    email: '',
    avatar: ''
  })

  // 是否为管理员
  const isAdmin = ref(userInfo.value.role === 'admin')
  
  // 是否为安全员
  const isSafetyOfficer = ref(userInfo.value.role === 'safety')
  
  // 是否为普通员工
  const isEmployee = ref(userInfo.value.role === 'employee')

  // 检查权限
  const hasPermission = (permission: string) => {
    if (userInfo.value.role === 'admin') {
      return true // 管理员拥有所有权限
    }
    return userInfo.value.permissions[permission] || false
  }

  // 检查是否可以访问页面
  const canAccessPage = (pageName: string) => {
    const pagePermissions = {
      'evaluation': ['evaluation'],
      'hazard': ['hazardTracking'],
      'reports': ['reportManagement'],
      'knowledge': ['knowledgeBase'],
      'users': ['userManagement'] // 只有管理员可以访问
    }
    
    if (userInfo.value.role === 'admin') {
      return true // 管理员可以访问所有页面
    }
    
    const requiredPermissions = pagePermissions[pageName] || []
    return requiredPermissions.some(permission => hasPermission(permission))
  }

  // 登录
  const login = (userData: any) => {
    // 更新用户信息
    userInfo.value = {
      id: userData.id || '',
      username: userData.username || '',
      name: userData.name || '',
      role: userData.role || '',
      permissions: userData.permissions || {},
      lastLoginTime: userData.lastLoginTime || '',
      status: userData.status || '',
      department: userData.department || '',
      position: userData.position || '',
      phone: userData.phone || '',
      email: userData.email || '',
      avatar: userData.avatar || ''
    }
    
    // 更新角色状态
    isAdmin.value = userData.role === 'admin'
    isSafetyOfficer.value = userData.role === 'safety'
    isEmployee.value = userData.role === 'employee'
    
    // 保存到localStorage
    localStorage.setItem('user-info', JSON.stringify(userInfo.value))
    
    console.log('用户登录信息已保存:', userInfo.value)
    
    return Promise.resolve()
  }

  // 登出
  const logout = () => {
    userInfo.value = {
      id: '',
      username: '',
      name: '',
      role: '',
      permissions: {},
      lastLoginTime: '',
      status: '',
      department: '',
      position: '',
      phone: '',
      email: '',
      avatar: ''
    }
    isAdmin.value = false
    isSafetyOfficer.value = false
    isEmployee.value = false
    
    // 清除localStorage
    localStorage.removeItem('user-info')
    
    console.log('用户登录信息已清除')
  }
  
  // 获取角色显示名称
  const getRoleDisplayName = () => {
    const roleNames = {
      'admin': '管理员',
      'safety': '安全员',
      'employee': '普通员工'
    }
    return roleNames[userInfo.value.role] || '未知角色'
  }

  return {
    userInfo,
    isAdmin,
    isSafetyOfficer,
    isEmployee,
    hasPermission,
    canAccessPage,
    login,
    logout,
    getRoleDisplayName
  }
})
